import React from 'react';
import {  connect } from 'react-redux';
import { message, Radio, Button, Row, Col, Input, Form, Icon, Upload } from 'antd';
import {formItemLayout, _validate, API_URL, _public_app, fetchLatestVersion} from '../../store/actions'

const RadioGroup = Radio.Group,
  RadioButton = Radio.Button,
  createForm = Form.create,
  FormItem = Form.Item;
let latest = {
  ios:{},
  android:{}
};
class _FormAppPublic extends React.Component{
    constructor(props){
        super(props);
        this.state = {
          type:''
        };
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleSubmit(e){
      try{
        const _this = this,
          token = _this.props.user.accessToken;
        _validate(e,_this,function(data){
          if(data.type == 'android'){
            data.app = _this.refs.app.files[0]
          }else if(data.type == 'ios'){
            const http = /^http/i,
              hasHttp = http.test(data.url),
              oldUrl = data.url;
            if(!hasHttp){
              data.url = `http://${oldUrl}`
            }
          }
          _public_app(token,data,function(){
            message.success(`发布成功！`);
            _this.context.router.push('/app-manage')
          },function(res){
            message.error(res.head.msg)
          },function(e){
            message.error(`请求失败，错误：${e}`)
          })
        })
      }catch(e){}
    }
    changeType(e){
        const _type = e.target.value;
        this.setState({
            type:_type
        })
    }
    renderAppFile(getFieldProps){
        if(this.state.type === 'ios'){
            const urlProps = getFieldProps('url', {
                rules: [
                    {required:true, message: '必须选择App类型' }
                ]
            });
            return (
              <FormItem
                {...formItemLayout}
                label="url"
              >
                  <Input {...urlProps} placeholder="请输入App下载地址" />
              </FormItem>
            )
        }else if(this.state.type === 'android'){
            const appProps = getFieldProps('app', {
                rules: [
                    {required:true, message: '必须选择android安装包' }
                ]
            });
            return (
              <FormItem
                {...formItemLayout}
                label="上传安装包"
              >
                  <input {...appProps} type="file" ref="app" name="app" />
              </FormItem>
            )
        }else{
            return ''
        }
    }
    componentWillMount(){
      this.props.dispatch(fetchLatestVersion('ios',function(res){
        if(res.head.msg == '没有版本信息'){
          latest.ios = {version:'-暂无'}
        }else{
          latest.ios = res.content
        }

      },function(){
        latest.ios = {version:'无'}
      }));
      this.props.dispatch(fetchLatestVersion('android',function(res){
        if(res.head.msg == '没有版本信息'){
          latest.android = {version:'-暂无'}
        }else{
          latest.android = res.content
        }
      },function(){
        latest.android = {version:'无最新版本'}
      }))
    }
    static contextTypes = {
      router: React.PropTypes.object
    }
    goBack(){
      this.context.router.push('/app-manage')
    }
    render(){
        const { getFieldProps } = this.props.form;
         const typeProps = getFieldProps('type', {
         rules: [
         {required:true, message: '必须选择App类型' }
         ],
         onChange:this.changeType.bind(this)
         });
         const nameProps = getFieldProps('name', {
         rules: [
         {required:true, message: 'App名称为必填项' },
         {max:24, message: 'App名称不能超过24个字符' }
         ]
         });
         const versionProps = getFieldProps('version', {
         rules: [
         {required:true, message: 'App版本号为必填项' }
         ]
         });
         const releaseProps = getFieldProps('release_notes', {
         rules: [
         {required:true, message: 'App发布备注为必填项' },
         {max:512, message: 'App名称不能超过512个字符' }
         ]
         });
        return (
               <Form horizontal form={this.props.form}>


                 <FormItem
                   {...formItemLayout}
                   label="类型"
                 >
                   <RadioGroup {...typeProps}>
                     <RadioButton value="ios">iOS</RadioButton>
                     <RadioButton value="android">Android</RadioButton>
                   </RadioGroup>
                 </FormItem>
                 <FormItem
                   {...formItemLayout}
                   label="名称"
                 >
                   <Input {...nameProps} placeholder="请输入App名称" />
                 </FormItem>
                 <FormItem
                   {...formItemLayout}
                   label="版本号"
                   help={`${this.state.type == ''?'尚未选择设备':(this.state.type == 'ios'?'iOS最新版'+latest.ios.version:'Android最新版'+latest.android.version)}`}
                 >
                   <Input {...versionProps} placeholder="请输入App版本号" />
                 </FormItem>

                 <FormItem
                   {...formItemLayout}
                   label="发布备注"
                 >
                   <Input type="textarea" autosize={{ minRows: 6, maxRows: 8 }} {...releaseProps} placeholder="请输入发布描述" />
                 </FormItem>
                 {this.renderAppFile(getFieldProps)}
                 <FormItem wrapperCol={formItemLayout.noLabel}>
                   <Button type="primary" onClick={this.handleSubmit}>发布</Button>
                   &nbsp;&nbsp;&nbsp;
                   <Button onClick={this.goBack.bind(this)}>返回</Button>
                 </FormItem>
               </Form>
        )
    }
}
_FormAppPublic= createForm()(_FormAppPublic);
let AppManage;
export default AppManage = connect((state)=>{
    const {user} = state.rootReducer;
    return {user}
})(_FormAppPublic)
